<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()" >
      <el-row>
        <el-col :span="15"  >
      <el-form-item  >
        <span style="font-size: 24px; font-weight: bold;" >设备台账</span>
      </el-form-item>
     </el-col> 
    <el-col :span="9"  >
      <el-form-item >
        <!-- <input type="file" id="folderInput" webkitdirectory directory multiple> -->
        <el-button size="small" type="primary" icon="el-icon-upload2" @click="dialogExcelVisible=true">上传台账表格</el-button>
        <el-button v-if="isAuth('dss:deviceInformation:export')" icon="el-icon-download" size="small" type="primary" @click="excelExport()">导出台账表格</el-button>
        <el-button  v-if="isAuth('dss:deviceInformation:save')" type="primary" size="small" @click="addOrUpdateHandle()"  icon="el-icon-plus">新增设备</el-button>
        <el-button  v-if="isAuth('dss:deviceInformation:delete')" type="danger" size="small" @click="deleteHandle()" :disabled="dataListSelections.length <= 0" icon="el-icon-delete">批量删除</el-button>
      </el-form-item>
      
    </el-col>
  </el-row>
      <div></div> 
      <el-row>
        <el-col :span="17"  >
       <!-- <el-form-item>  
        <el-input v-model="dataForm.deviceName" placeholder="请输入设备名称"  clearable class="input-with-select">
          <template slot="prepend">设备名称</template>
       </el-input>
      </el-form-item> -->
      <el-form-item style="font-size: 24px; font-weight: bold;" >设备检索：</el-form-item>  
       <el-form-item   >  
        <el-input v-model="dataForm.deviceInformation" placeholder="请输入内容"  clearable class="input-with-select" >
          <el-select v-model="select" slot="prepend" placeholder="查询索引">
      <el-option label="设备名称" value="deviceName"></el-option>
      <el-option label="设备编号" value="deviceId"></el-option>
      <el-option label="设备型号" value="deviceModel"></el-option>
    </el-select>
    <el-button slot="append" icon="el-icon-search"  class="green-button" @click="search()"></el-button>
       </el-input>
      </el-form-item> </el-col>
      <el-col :span="7"  >
        <el-form-item style="font-size: 24px; font-weight: bold;" >设备筛选：</el-form-item>  
      <el-form-item >
      <el-select v-model="dataForm.lightStatus" placeholder="设备的状态" clearable   @change="search()">
        <el-option label="正常" value=1></el-option>
        <el-option label="保养中" value=0></el-option >
        <el-option label="故障" value=-1></el-option>
      </el-select>
    </el-form-item>
    <el-form-item >
      <el-select v-model="dataForm.selectedFilter" placeholder="设备的年龄" clearable   @change="search()">
        <el-option label="一年以内" value="一年以内"></el-option>
        <el-option label="三年以内但大于一年" value="超过1年但小于等于3年"></el-option >
        <el-option label="三年以后" value="三年以后"></el-option>
      </el-select>
    </el-form-item>
  </el-col>
 
  </el-row>
               <!-- 上传excel的对话框 -->
  <el-dialog title="上传设备台账表格" :visible.sync="dialogExcelVisible" width="25%">
    <el-upload v-if="isAuth('dss:deviceInformation:upload')" class="upload-demo" name="file" drag accept=".xlsx" :on-success="uploadExcelSuccess"
      :on-error="uploadExcelError" :action="this.$http.adornUrl(`/dss/deviceInformation/upload/excel`)" :headers="tokenInfo" :show-file-list="false">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传.xlsx文件</div>
    </el-upload>
  </el-dialog>

   
    </el-form>
    <el-table height="648" :row-class-name="tableRowClassName" :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;" :default-sort="{ prop:'launchTime', order:'descending' }" @sort-change="sortChange">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column type="index"  header-align="center" align="center" label="序号"></el-table-column>
      <el-table-column prop="workshopName" header-align="center" align="center" label="车间名称">
      </el-table-column> 
      <el-table-column prop="name" header-align="center" align="center" label="设备类型"   :filters="this.types" :filter-method="filterHandler"></el-table-column>
      <el-table-column prop="deviceId" header-align="center" align="center"  label="设备编号"></el-table-column>
     
      <el-table-column prop="deviceName" header-align="center" align="center" label="设备名称"></el-table-column>
      <el-table-column prop="deviceModel" header-align="center" align="center" label="设备型号"></el-table-column>
      <el-table-column prop="lightStatus" header-align="center" align="center" label="设备状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.lightStatus === 1 "   type="success" >运行</el-tag>
          <el-tag v-else-if="scope.row.lightStatus === 0 "  type="warning">保养中</el-tag>
          <el-tag v-else-if="scope.row.lightStatus === -1"  type="danger" >故障</el-tag>
          
        </template>
      </el-table-column>
      <!-- <el-table-column prop="factory" header-align="center" align="center" label="制造厂"></el-table-column> -->
      <el-table-column prop="produceTime" header-align="center" align="center" label="生产日期"   sortable  width="130">   
        <template slot-scope="scope">
        <i v-if="scope.row.produceTime" class="el-icon-date"></i>
        <span style="margin-left: 10px">{{ scope.row.produceTime }}</span>
      </template>
    </el-table-column>
      <el-table-column prop="startUseTime" header-align="center" align="center" label="开始使用日期" sortable width="130">
        <template slot-scope="scope">
        <i v-if="scope.row.produceTime" class="el-icon-date"></i>
        <span style="margin-left: 10px">{{ scope.row.startUseTime }}</span>
      </template>
      </el-table-column>
      <el-table-column prop="maintenanceTime" header-align="center" align="center" label="维保到期" sortable width="130">
        <template slot-scope="scope">
        <i v-if="scope.row.produceTime" class="el-icon-date"></i>
        <span style="margin-left: 10px">{{ scope.row.maintenanceTime }}</span>
      </template>
      </el-table-column>
      <el-table-column type="expand"  label="详情" >
      <template slot-scope="props" > 
        <el-form  label-position="left"  class="demo-table-expand" >
          <el-row>
            <el-col :span="12"  > 
          <el-form-item label="制造厂 :" >
            <span  :style="{ fontSize: '14px' }">{{ props.row.factory }}</span>
          </el-form-item>
          </el-col>
          <el-form-item label="传感器ID :">
            <span  :style="{ fontSize: '14px' }">{{ props.row.sensorId }}</span>
          </el-form-item>
        </el-row>
          <el-form-item label="备注 :" >
            <span  :style="{ fontSize: '14px' }" >{{ props.row.notes }}</span>
          </el-form-item>
          <el-form-item label="设备视频 :">
  <video  v-if="props.row.video" :src="props.row.video"  controls  style="width: 300px; max-height: 200px; border-radius: 4px" preload="metadata">您的浏览器不支持视频播放</video>
  <span v-else style="font-size:14px">无视频</span>
</el-form-item>
        </el-form>
      </template>
    </el-table-column>
      <!-- <el-table-column prop="notes" header-align="center" align="center" label="备注"></el-table-column>
      <el-table-column prop="sensorId" header-align="center" align="center" label="传感器ID"></el-table-column> -->
      <el-table-column fixed="right" header-align="center" align="center" width="200" label="操作">
        <template slot-scope="scope">

          <el-button v-if="isAuth('dss:deviceInformation:update')"   type="info" icon="el-icon-edit" round size="mini" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button v-if="scope.row.followId" type="text"  icon="el-icon-star-on" style=" " circle @click=" followDeleteHandle(scope.row.followId,scope.row.deviceId)"></el-button>
          <el-button v-if="!scope.row.followId" type="text"  icon="el-icon-star-off"  circle @click=" followSubmit(scope.row.deviceId)"></el-button>
          <el-button v-if="isAuth('dss:deviceInformation:delete')" type="danger"  icon="el-icon-delete" circle size="mini"  @click="deleteHandle(scope.row.id,scope.row.deviceId)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
      :total="totalCount" layout="total,sizes,prev,pager,next,jumper"></el-pagination>
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>
<style>
  .el-select .el-input {
    width: 130px;
   
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
    color: rgb(14, 14, 14);
  }
  .input-with-select .el-input-group__append:hover {
    background-color: #9cc8e8; 
    border-color: #6a8bbc; 
    color: rgb(250, 250, 250);
  }


  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    font-size: 15px;
    width: 90px;
    color: #090a0b;
    
  }
  .demo-table-expand .el-form-item {
     
    margin-left: 0;
    margin-bottom: 0;
    width: 200%;
  }
</style>

<script>
import AddOrUpdate from './deviceinformation-add-or-update'

  export default{
    data(){
      return {
       tokenInfo: {
          'token': this.$cookie.get('token')
        },
        dialogExcelVisible:false,
        select:'',
        types:[],
        dataForm:{
          deviceInformation:'',
          deviceId:'',
          deviceName:'',
          selectedFilter:'',
          lightStatus:'',
          avatar:''
        },
        dataList:[],
        pageIndex:1,
          pageSize:10,
        totalCount:0,
        dataListLoading:false,
        dataListSelections:[],
         addOrUpdateVisible:false,
      }
    },
    components:{
      AddOrUpdate,
    },
    activated(){
      this.getDataList()
    },
    methods:{
      open() {
        this.$notify({
          title: '警告',
          message: '上传文档录入的设备，保养计划都为"设备到达480小时后进行保养预警"',
          type: 'warning'
        });
      },
     excelExport(){
      console.log(this.dataForm.selectedFilter);
        this.$http({
    url: this.$http.adornUrl(`/dss/deviceInformation/export/excel`),
    method: 'get',
    responseType: 'blob' ,// 必须声明响应类型为二进制流
    params:this.$http.adornParams({
            'page':this.pageIndex,
              'limit':this.pageSize,
            'deviceId':this.dataForm.deviceId,
            'deviceInformation':this.dataForm.deviceInformation,
            'selectedFilter':this.dataForm.selectedFilter,
            'select':this.select,
            'lightStatus':this.dataForm.lightStatus,
           })
  }).then(response => {
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data])) // 将响应数据转为临时URL字符串，Blob二进制流
    const link = document.createElement('a')// 创建虚拟<a>标签超链接元素，<a> 标签的download是HTML5标准中唯一能强制触发文件下载的浏览器的属性
    link.href = url// 绑定文件URL
    link.setAttribute('download', '设备台账.xlsx') // 设置文件名， 强制浏览器下载而非打开
    document.body.appendChild(link)// 将链接插入页面才能触发下载
    link.click() // 模拟点击下载
    link.remove() // 下载完成后移除元素避免内存泄漏
  }).catch(error => {
    this.$message.error('导出失败：' + (error.message || '服务器异常'))// 显示错误提示
  })
  },  
      uploadExcelSuccess(response, file, fileList){
        if(response.code === 0) {    // 根据R.code判断成功
    this.$message({
    type:"success",
    duration:3000, 
    message:response.msg
    
  }) // 显示后端消息
    this.getDataList()         // 带括号执行方法
    
      this.open()
    
  }else if(response.code === 400){
    this.$message({
    type:"error",
    duration:3000, 
    message:response.msg
  })}else if(response.code === 300){
    this.$message({
    type:"warning",
    duration:3000, 
    message:response.msg
  })}else {
    this.$message.error(response.msg)    // 显示失败原因
  }
  this. dialogExcelVisible=false
           },
uploadExcelError(err){
  this.$message({
    type:"error",
    message:err
  })
},
      filterHandler(value, row, column) {
        const property = column['property'];
        return row[property] === value;
      },
      // tableRowClassName({row, rowIndex}) {
      //   if (rowIndex === 1) {
      //     return 'maintenance-row';
      //   } else if (rowIndex === 3) {
      //     return 'fault-row';
      //    }//else if(rowIndex===2){
      //   //   return 'run-row'
      //   // }
      //   return '';
      // },
      search() { 
        this.pageIndex=1
        this.getDataList()
      },
      getDataList(){
        this.dataListLoading=true
        this.$http({
          url:this.$http.adornUrl('/dss/deviceInformation/list'),
          method:'get',
          params:this.$http.adornParams({
            'page':this.pageIndex,
              'limit':this.pageSize,
            'deviceId':this.dataForm.deviceId,
            'deviceInformation':this.dataForm.deviceInformation,
            'selectedFilter':this.dataForm.selectedFilter,
            'select':this.select,
            'lightStatus':this.dataForm.lightStatus

          })
        }).then(({data})=>{
          if (data && data.code===0){
        
            this.dataList=data.page.list
            this.totalCount=data.page.totalCount
            this.types = [...new Set(this.dataList.map(item => item.name))].map(name => {
              return { text: name, value: name }})    
              console.log(this.dataList)
          }else{
            this.dataList=[]
            this.totalCount=0
          }
          this.dataListLoading=false
        })
      },
      sortChange(column){
          this.isAsc=column.order=="ascending"?'asc':'desc'
     
        this.getDataList()
      },
      sizeChangeHandle(val){
        this.pageSize=val
        this.pageIndex=1
        this.getDataList()
      },
      currentChangeHandle(val){
        this.pageIndex=val
        this.getDataList()
      },
      selectionChangeHandle(val){
        this.dataListSelections=val
      },
      addOrUpdateHandle(id){
        this.addOrUpdateVisible=true
        this.$nextTick(()=>{
          this.$refs.addOrUpdate.init(id,this.dataList)
        })
      },
      deleteHandle(id,deviceId){
        console.log(deviceId)
        var deviceIds=deviceId?[deviceId]:this.dataListSelections.map(item=>{
          return item.deviceId
        })
        var ids=id?[id]:this.dataListSelections.map(item=>{
          return item.id
        })
        this.$confirm(`确定对[设备编号为${deviceIds.join(',')}]的设备进行[${deviceId?'删除':'批量删除'}]操作?`,'提示', {
          confirmButtonText:'确定',
           cancelButtonText:'取消',
          type:'warning'
        }).then(()=>{
          this.$http({
            url:this.$http.adornUrl('/dss/deviceInformation/delete'),
            method:'post',
            data:this.$http.adornData(ids,false)
          }).then(({data})=>{
            if (data && data.code===0){
              this.$message({
                 message:'操作成功',
                type:'success',
                duration:1500, 
                 onClose:()=>{
                  this.getDataList()
                }
              })
            }else{
              this.$message.error(data.msg)
            }
          })
        }).catch(()=>{})
      },
      followSubmit(deviceId){
        console.log(deviceId);
          if (deviceId){
            var deviceIds=deviceId?[deviceId]:this.deviceId.map(item=>{
          return item.deviceId
        })
            this.$http({
              url:this.$http.adornUrl(`/dss/follow/save`),
              method:'post',
              data:this.$http.adornData(deviceIds,false)
            }).then(({data})=>{
              if (data&&data.code===0) {
                 this.getDataList()
                this.$message({
                  message:'关注成功',
                  type:'success',
                  duration:800,
              
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        
      },
      followDeleteHandle(id,deviceId){
        
       var deviceIds=deviceId?[deviceId]:this.dataListSelections.map(item=>{
         return item.deviceId
       })
       var ids=id?[id]:this.dataListSelections.map(item=>{
         return item.id
       }) 
    // console.log(ids)
    //    this.$confirm(
    //     `确定对[设备编号为${deviceIds.join(',')}]的设备进行[${deviceId?'取消关注':'批量取关'}]操作?`,'提示', {
    //      confirmButtonText:'确定',
    //       cancelButtonText:'取消',
    //      type:'warning'
    //    }
    //   ).then(()=>{
         this.$http({
           url:this.$http.adornUrl('/dss/follow/delete'),
           method:'post',
           data:this.$http.adornData(ids,false)
         }).then(({data})=>{
           if (data && data.code===0){
             this.getDataList()
             this.$message({
                message:'取消关注成功',
               type:'warning',
               duration:800, 
             })
           }else{
             this.$message.error(data.msg)
           }
         })
      //  }).catch(()=>{})
     }
    }
  }
</script>
